package com.smartHome.controller;

import com.smartHome.pojo.dto.HouseDTO;
import com.smartHome.pojo.entity.Result;
import com.smartHome.pojo.vo.HouseDetailVO;
import com.smartHome.pojo.vo.HouseListVO;
import com.smartHome.pojo.vo.HouseVO;
import com.smartHome.service.HouseService;
import com.smartHome.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

@RestController
@RequestMapping("/house")
public class HouseController {

    @Autowired
    private HouseService houseService;

    @GetMapping("/list")
    public Result<Map<String, List<HouseListVO>>> listHouses() {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        List<HouseListVO> houses = houseService.getAllHousesWithMembers(userId);
        Map<String, List<HouseListVO>> response = new HashMap<>();
        response.put("houses", houses);
        return Result.success(response);
    }

    @GetMapping("/getHouse")
    public Result<List<HouseVO>> getHouseByUserId() {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        List<HouseVO> houseList = houseService.getByUserId(userId);
        return Result.success(houseList);
    }

    @GetMapping("/onlineDevices/{houseId}")
    public Result<Integer> getHouseOnlineDevices(@PathVariable Integer houseId) {
        Integer onlineDevices = houseService.getHouseOnlineDevices(houseId);
        return Result.success(onlineDevices);
    }

    @PostMapping("/addHouse")
    public Result<Void> addHouse(@RequestBody HouseDTO houseDTO) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        String houseName = houseDTO.getHouseName();
        houseService.addHouse(userId, houseName);
        return Result.success();
    }

    @PostMapping("/deleteHouses")
    public Result<Void> deleteHouses(@RequestBody List<Integer> houseIds) {
        houseService.deleteHouses(houseIds);
        return Result.success();
    }

    @GetMapping("/houseDetail/{houseId}")
    public Result<HouseDetailVO> getHouseDetail(@PathVariable Integer houseId) {
        HouseDetailVO houseDetail = houseService.getHouseDetail(houseId);
        return Result.success(houseDetail);
    }
}
